<template>
  <PageLayout title="首页">
	<view class="container" :class="{'search-hidden-mode': isSearchHidden}">
		<!-- 搜索栏 -->
		<view class="search-container" :class="{'search-hidden': isSearchHidden}" :style="{top: `${statusBarHeight + navBarHeight}px`}">
			<view class="search-box" @tap="goToSearch">
				<uni-icons type="search" size="18" color="#c0c4cc"></uni-icons>
				<text class="placeholder">搜索内容</text>
			</view>
			<view class="navbar-actions">
				<view class="action-btn message-btn" @tap="goToMessage">
					<uni-icons type="chatbubble" size="24" color="#333333"></uni-icons>
					<uni-badge :text="unreadMsgCount > 0 ? unreadMsgCount : ''" type="error" :max-num="99"
						absolute="rightTop" />
				</view>
			</view>
		</view>

		<!-- 分类标签 -->
		<view class="category-tabs-container" :style="{top: getCategoryTabsTopPx() + 'px'}">
			<scroll-view scroll-x class="category-tabs" show-scrollbar="false" :enhanced="true" :showScrollbar="false">
				<text v-for="(item, index) in categories" :key="index"
					:class="['tab-item', currentCategory === index ? 'active' : '']"
					@tap="switchCategory(index)">{{item.name}}</text>
			</scroll-view>
		</view>

		<!-- 帖子列表 -->
		<view class="post-list">
			<uni-list :border="false" :customStyle="{ backgroundColor: 'transparent', padding: '0 20rpx', margin: 0 }">
				<uni-list-item v-for="(post, index) in postList" :key="index" :to="'/pages/post/detail?id='+post.id"
					clickable :border="false" :padding="false" :margin="0"
					:customStyle="{ backgroundColor: '#ffffff', borderRadius: '16rpx', padding: '30rpx 30rpx 30rpx', marginBottom: '20rpx', boxSizing: 'border-box' }"
					class="post-item">
					<!-- 使用footer插槽作为占位 -->
					<template v-slot:footer></template>

					<!-- 帖子内容 -->
					<template v-slot:body>
						<view class="post-content">
							<text class="post-title">{{post.title}}</text>

							<!-- 作者信息和发布时间 -->
							<view class="author-info">
								<view class="name-level">
									<text class="author-name">{{post.author.name}}</text>
									<text class="publish-time">· {{post.publishTime}}发布</text>
								</view>
							</view>

							<text class="post-text">{{post.content}}</text>
							<!-- 话题标签 -->
							<view class="post-topic" v-if="post.topic">
								<uni-tag :text="post.topic" type="primary" size="small" :circle="true"
									:inverted="true"></uni-tag>
							</view>

							<!-- 底部操作栏 -->
							<view class="post-actions">
								<view class="action-item" @tap.stop="likePost(post)">
									<uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="22"
										:color="post.isLiked ? '#ff4d4f' : '#999'"></uni-icons>
									<text class="count">{{post.likeCount || 0}}</text>
								</view>
								<view class="action-item">
									<uni-icons type="chatbubble" size="22" color="#999"></uni-icons>
									<text class="count">{{post.commentCount || 0}}</text>
								</view>
							</view>
						</view>
					</template>

					<!-- 使用header插槽显示默认内容 -->
					<template v-slot:header>
						<view style="height: 2rpx;"></view> <!-- 占位元素 -->
					</template>
				</uni-list-item>
			</uni-list>

			<!-- 加载更多 -->
			<view class="load-more" v-if="postList.length > 0">
				<view v-if="loadMoreStatus === 'loading'" class="loading">
					<view class="loading-icon"></view>
					<text class="loading-text">加载中...</text>
				</view>
				<text v-else-if="loadMoreStatus === 'noMore'" class="no-more">没有更多内容了</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="postList.length === 0 && !isLoading">
				<uni-icons type="info" size="64" color="#cccccc"></uni-icons>
				<text class="empty-text">暂无内容</text>
			</view>
    </view>
  </view>
  </PageLayout>
</template>

<script>
import {onMounted, ref, computed} from 'vue';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue';
import uniBadge from '@dcloudio/uni-ui/lib/uni-badge/uni-badge.vue';
import uniList from '@dcloudio/uni-ui/lib/uni-list/uni-list.vue';
import uniListItem from '@dcloudio/uni-ui/lib/uni-list-item/uni-list-item.vue';
import uniGrid from '@dcloudio/uni-ui/lib/uni-grid/uni-grid.vue';
import uniGridItem from '@dcloudio/uni-ui/lib/uni-grid-item/uni-grid-item.vue';
import uniTag from '@dcloudio/uni-ui/lib/uni-tag/uni-tag.vue';
import PageLayout from "@/components/PageLayout.vue";
import useSafeArea from '@/composables/useSafeArea'

const {safeAreaHeight} = useSafeArea()
console.log("safeAreaHeight:", safeAreaHeight);

export default {
		components: {
      PageLayout,
			uniIcons,
			uniNavBar,
			uniBadge,
			uniList,
			uniListItem,
			uniGrid,
			uniGridItem,
			uniTag,
		},
		setup() {
			// 状态栏高度
			const statusBarHeight = ref(0);
			const navBarHeight = ref(44); // 默认导航栏高度
			
			// 搜索栏显示状态
			const isSearchHidden = ref(false);
			const scrollTop = ref(0);
			let lastScrollTop = 0;
			
			// 计算分类标签位置
			const getCategoryTabsTop = () => {
				if (isSearchHidden.value) {
					return `calc(var(--status-bar-height) + var(--nav-bar-height))`;
				} else {
					return `calc(var(--status-bar-height) + var(--nav-bar-height) + 72rpx)`;
				}
			};
			
			// 监听页面滚动
			const handlePageScroll = (e) => {
				const currentScrollTop = e.scrollTop;
				
				// 向下滚动超过50px时隐藏搜索栏
				if (currentScrollTop > lastScrollTop && currentScrollTop > 50) {
					isSearchHidden.value = true;
				} 
				// 向上滚动时显示搜索栏
				else if (currentScrollTop < lastScrollTop) {
					// 当用户向上滚动，重新显示搜索栏
					isSearchHidden.value = false;
				}
				
				lastScrollTop = currentScrollTop;
				scrollTop.value = currentScrollTop;
			};
			
			// 修改内联样式的动态计算
			const headerHeight = computed(() => {
				return statusBarHeight.value + navBarHeight.value;
			});

			// 初始化时确保搜索栏显示
			onMounted(() => {
				// 获取系统信息
				const sysInfo = uni.getSystemInfoSync();
				statusBarHeight.value = sysInfo.statusBarHeight;
				navBarHeight.value = 44; // 设置固定导航栏高度
				
				// 设置页面底部安全区域
				uni.setTabBarStyle({
					backgroundColor: '#ffffff'
				});
				
				// 确保初始状态下搜索栏显示
				isSearchHidden.value = false;
				
				// 加载数据
				fetchPostList();
			});

			// 导航状态
			const unreadMsgCount = ref(5);

			// 分类数据
			const categories = ref([{
					id: 1,
					name: '推荐'
				},
				{
					id: 2,
					name: '最新'
				},
				{
					id: 3,
					name: '热门'
				},
				{
					id: 4,
					name: '关注'
				},
				{
					id: 5,
					name: '附近'
				},
				{
					id: 6,
					name: '视频'
				},
				{
					id: 7,
					name: '同城'
				},
			]);
			const currentCategory = ref(0);

			// 列表数据
			const postList = ref([]);
			const isLoading = ref(true);
			const loadMoreStatus = ref('more'); // more, loading, noMore
			const iconType = ref('snow');
			const page = ref(1);
			const pageSize = ref(10);
			const hasMore = ref(true);

			// 获取帖子列表
			const fetchPostList = async (reset = false) => {
				if (reset) {
					page.value = 1;
					postList.value = [];
					hasMore.value = true;
				}

				if (!hasMore.value) return;

				isLoading.value = true;
				loadMoreStatus.value = 'loading';

				try {
					// 模拟请求
					setTimeout(() => {
						const mockData = generateMockData();

						if (reset) {
							postList.value = mockData;
						} else {
							postList.value = [...postList.value, ...mockData];
						}

						// 模拟分页
						if (page.value >= 3) {
							hasMore.value = false;
							loadMoreStatus.value = 'noMore';
						} else {
							page.value += 1;
							loadMoreStatus.value = 'more';
						}

						isLoading.value = false;
					}, 1000);
				} catch (error) {
					console.error('获取帖子列表失败', error);
					isLoading.value = false;
					loadMoreStatus.value = 'more';
				}
			};

			// 生成模拟数据
			const generateMockData = () => {
				return Array.from({
					length: 10
				}, (_, i) => ({
					id: `post_${page.value}_${i}`,
					title: `这是第${page.value}页第${i+1}条帖子的标题，展示岚迹APP的功能和体验`,
					content: '岚迹APP是一款专注于社交互动和内容分享的平台，通过丰富的功能和良好的用户体验，帮助用户建立连接、分享生活精彩瞬间，探索更多可能性。我们致力于打造一个安全、友好、积极向上的社区环境。'
						.repeat(Math.floor(Math.random() * 3) + 1),
					publishTime: '10分钟前',
					images: Math.random() > 0.3 ? Array.from({
								length: Math.floor(Math.random() * 6) + 1
							}, (_, j) =>
							`https://picsum.photos/id/${(i * 10 + j + page.value * 100) % 100}/300/300`) :
						[],
					showImages: [],
					topic: Math.random() > 0.5 ? ['生活记录', '美食分享', '旅行日记', '每日穿搭', '读书心得'][Math.floor(Math
						.random() * 5)] : '',
					author: {
						id: `user_${i}`,
						name: `用户${i + page.value * 10}`,
						avatar: `https://i.pravatar.cc/100?img=${(i + page.value * 10) % 70}`
					},
					likeCount: Math.floor(Math.random() * 1000),
					commentCount: Math.floor(Math.random() * 100),
					shareCount: Math.floor(Math.random() * 50),
					isLiked: Math.random() > 0.7
				})).map(post => {
					// 限制展示图片数量
					post.showImages = post.images.slice(0, 3);
					return post;
				});
			};

			// 切换分类
			const switchCategory = (index) => {
				if (currentCategory.value === index) return;
				currentCategory.value = index;
				fetchPostList(true);
			};

			// 点赞帖子
			const likePost = (post) => {
				post.isLiked = !post.isLiked;
				post.likeCount = post.isLiked ? (post.likeCount || 0) + 1 : (post.likeCount || 1) - 1;
				uni.showToast({
					title: post.isLiked ? '已点赞' : '已取消点赞',
					icon: 'none'
				});
			};

			// 预览图片
			const previewImage = (images, current) => {
				uni.previewImage({
					urls: images,
					current: current
				});
			};

			// 跳转发布页
			const goToPublish = () => {
				uni.navigateTo({
					url: '/pages/publish/index'
				});
			};

			// 跳转搜索页
			const goToSearch = () => {
				uni.navigateTo({
					url: '/pages/search/index'
				});
			};

			// 跳转消息页
			const goToMessage = () => {
				uni.navigateTo({
					url: '/pages/message/index'
				});
			};

			// 计算分类标签位置
			const getCategoryTabsTopPx = () => {
				// 搜索栏高度为36px (72rpx)
				if (isSearchHidden.value) {
					return headerHeight.value;
				} else {
					return headerHeight.value + 36;
				}
			};

    return {
				statusBarHeight,
				navBarHeight,
				headerHeight,
				isSearchHidden,
				scrollTop,
				handlePageScroll,
				getCategoryTabsTop,
				getCategoryTabsTopPx,
				unreadMsgCount,
				categories,
				currentCategory,
				postList,
				isLoading,
				loadMoreStatus,
				iconType,
				switchCategory,
				likePost,
				previewImage,
				goToPublish,
				fetchPostList,
				goToSearch,
				goToMessage
			};
		},
		// 页面生命周期函数 - 下拉刷新
		onPullDownRefresh() {
			this.fetchPostList(true).then(() => {
				uni.stopPullDownRefresh();
			});
		},
		// 页面生命周期函数 - 上拉加载
		onReachBottom() {
			if (!this.isLoading && this.loadMoreStatus !== 'noMore') {
				this.fetchPostList();
			}
		},
		// 页面滚动事件
		onPageScroll(e) {
			this.handlePageScroll(e);
		}
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: env(safe-area-inset-bottom);
  box-sizing: border-box;
  overflow-x: hidden; // 防止横向滚动

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  // 当搜索栏隐藏时应用的样式
  &.search-hidden-mode {
    .category-tabs-container {
      // 这里不再使用CSS变量，而是通过行内样式控制
      // top属性已通过getCategoryTabsTopPx()动态设置
    }
    
    .post-list {
      padding-top: 150px;  // 减去搜索栏高度
      transition: padding-top 0.3s ease-out;
    }
  }

  // 搜索区域
  .search-container {
    position: fixed;
    left: 0;
    right: 0;
    height: 72rpx;
    background-color: #ffffff;
    z-index: 996;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    box-sizing: border-box;
    transition: transform 0.3s ease;
  }
  
  .search-hidden {
    transform: translateY(-100%);
    transition: transform 0.3s ease;
  }

  .search-box {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 16rpx;
    height: 72rpx;
    padding: 0 20rpx;
    flex: 1;
    margin-right: 16rpx;

    .placeholder {
      color: #999;
      font-size: 28rpx;
      margin-left: 10rpx;
      flex: 1;
    }
  }

  .navbar-actions {
    display: flex;
    align-items: center;

    .action-btn {
      position: relative;
      padding: 0;
      margin-left: 0;

      &.message-btn {
        width: 80rpx;
        height: 72rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .category-tabs-container {
    position: fixed;
    left: 0;
    right: 0;
    z-index: 995;
    background-color: #ffffff;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
    transition: top 0.3s ease;
  }

  .category-tabs {
    white-space: nowrap;
    background-color: #ffffff;
    padding: 15rpx 20rpx;
    height: 100rpx;
    box-sizing: border-box;
    
    :deep(::-webkit-scrollbar) {
      display: none;
      width: 0;
      height: 0;
      color: transparent;
    }

    .tab-item {
      display: inline-block;
      font-size: 30rpx;
      color: #666;
      padding: 0 30rpx;
      position: relative;

      &.active {
        color: #2979ff;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: -8rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 6rpx;
          background-color: #2979ff;
          border-radius: 6rpx;
        }
      }
    }
  }
  
  .uni-list {
    background-color: #f8f8f8;
  }
  
  .post-list {
    flex: 1;
    padding: 0;
    padding-top: 86px;
    padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
    background-color: #f8f8f8;
    transition: padding-top 0.3s ease-out;
    width: 100%;
    box-sizing: border-box;
    position: relative;
    
    .post-item {
      margin-bottom: 20rpx !important;
      margin-left: 0 !important; 
      margin-right: 0 !important;
      border-radius: 8rpx !important; // 增加圆角
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05); // 添加阴影效果
      overflow: hidden; // 确保内容不溢出
    }

    .author-info {
      margin-bottom: 16rpx;

      .name-level {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .author-name {
          font-size: 26rpx;
          color: #666;
          margin-right: 10rpx;
          font-weight: 500;
        }

        .publish-time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .post-content {
      margin-top: 10rpx;
      display: flex;
      flex-direction: column;

      .post-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
        line-height: 1.4;
        display: block;
      }

      .post-text {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        display: block;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        margin-bottom: 20rpx;
        max-height: none;
      }

      .expand-btn {
        font-size: 28rpx;
        color: #2979ff;
        margin-top: 10rpx;
        display: inline-block;
      }
    }

    .post-media {
      position: relative;
      margin-top: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 12rpx;
      overflow: hidden;

      .grid-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
        object-fit: cover;
      }

      .image-count {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        background-color: rgba(0, 0, 0, 0.6);
        color: #fff;
        font-size: 24rpx;
        padding: 4rpx 16rpx;
        border-radius: 20rpx;
      }
    }

    .post-topic {
      margin-top: 16rpx;
      margin-bottom: 20rpx;
    }

    .post-actions {
      display: flex;
      margin-top: 25rpx;
      background-color: transparent;
      border-top: 1px solid #f5f5f5;
      padding-top: 20rpx;
    }

    .action-item {
      display: flex;
      align-items: center;
      margin-right: 40rpx;
      background-color: transparent;
      
      .count {
        font-size: 26rpx;
        color: #999;
        margin-left: 8rpx;
      }
    }
  }

  .load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx 20rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    background-color: transparent;

    .loading {
      display: flex;
      align-items: center;
      margin-right: 10rpx;

      .loading-icon {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        border: 2rpx solid #999;
        border-top-color: #2979ff;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    .no-more {
      font-size: 28rpx;
      color: #999;
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx;

    .empty-text {
      font-size: 28rpx;
      color: #999;
      margin-top: 20rpx;
    }
  }
}
</style>